package com.example.makerspace.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.makerspace.dao.*;
import com.example.makerspace.domain.*;
import com.example.makerspace.dto.*;
import com.example.makerspace.service.ExpertService;
import com.example.makerspace.utils.FileConvertUtil;
import com.example.makerspace.utils.FileUtils;
import com.example.makerspace.utils.JwtUtils;
import com.example.makerspace.utils.ValidateCodeUtils;
import com.example.makerspace.vo.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ExpertServiceImpI implements ExpertService {
    @Resource
    private ExpertInfoDAO expertInfoDAO;

    @Resource
    private ExpertClassifyDAO expertClassifyDAO;

    @Resource
    private DemandDAO demandDAO;

    @Resource
    private ExpertTaskDAO expertTaskDAO;

    @Resource
    private ExpertProductScoreDAO expertProductScoreDAO;

    @Resource
    private ExpertOutcomeDAO expertOutcomeDAO;

    @Resource
    private TaskOutcomeScoreDAO taskOutcomeScoreDAO;

    @Resource
    private  TaskOutComeReviewDAO taskOutComeReviewDAO;

    @Resource
    private  ExpertTaskStateDAO expertTaskStateDAO;


    @Resource
    private UserDAO userDAO;
  private  final  static  String   testHttpPrefix="https://119.45.199.13:3035/static/";


   private  final  static  String  devHttpPrefix="https://nism.ytcata.com:443/static/";
    private final static String DEMAND_PICTURE_PATH_PREFIX = "demand/";

    @Override
    public Result showExpertList(PageRequest pageRequest) {
        IPage<ExpertInfoDO> expertInfoDOIPage = null;
        Map<String, Object> params = pageRequest.getParams();
        Pagination pagination = pageRequest.getPagination();
        String type = MapUtils.getString(params, "type");
        String name = MapUtils.getString(params, "name");
        if (type.equals("")&&name.equals("")) {
            expertInfoDOIPage = expertInfoDAO.selectByPageIsShow(pagination);
            return Result.success(expertInfoDOIPage);
        }
        else if(type.equals("")&&!name.equals("")){
            expertInfoDOIPage = expertInfoDAO.selectByPageLikeName(pagination,name);
            return  Result.success(expertInfoDOIPage);
        }
        else if(!type.equals("")&&name.equals("")){
            expertInfoDOIPage = expertInfoDAO.selectByPageAndType(pagination, type);
            return Result.success(expertInfoDOIPage);
        }else if(!type.equals("")&&!name.equals("")){
            expertInfoDOIPage = expertInfoDAO.selectByPageAndTypeName(pagination, type, name);
            return  Result.success(expertInfoDOIPage);
        }
        else {
            return  Result.success(expertInfoDOIPage);
        }
    }

    public String phoneSecrecy(String phoneNum){
        if(phoneNum != null && phoneNum.length() > 4){
            if(phoneNum.length() == 11){
                phoneNum = phoneNum.substring(0, 3) + "****" + phoneNum.substring(7, phoneNum.length());
            }else{
                phoneNum = phoneNum.substring(0,phoneNum.length()-1) + "*";
            }
        }
        return phoneNum;
    }

    public  String cardSecrecy(String cardNum){
        if (cardNum.length() > 4) {
            String startNum = cardNum.substring(0, 4);
            String endNum = cardNum.substring(cardNum.length() - 4, cardNum.length());
            cardNum = startNum + "********" + endNum;
        }
        return  cardNum;
    }
    @Override
    public Result showExpertDetail(Integer id) {
        ExpertInfoDO expertInfoDO = expertInfoDAO.selectById(id);
        expertInfoDO.setPhone(phoneSecrecy(expertInfoDO.getPhone()));
        if(expertInfoDO.getIdentityCard()!=null){
            String identityCard = expertInfoDO.getIdentityCard();
            String inoNumber = identityCard.substring(0, 7) + "****" + identityCard.substring(11, identityCard.length());
            expertInfoDO.setIdentityCard(inoNumber);
        }
        if(expertInfoDO.getBankCardNumber()!=null){
            expertInfoDO.setBankCardNumber(cardSecrecy(expertInfoDO.getBankCardNumber()));
        }
        return Result.success(expertInfoDO);
    }

    @Override
    public Result addExpert(ExpertInfoDTO expertInfoDTO) {
        ArrayList<Integer> taskList = new ArrayList<>();
        UserDO userDO = new UserDO();
        ExpertInfoDO expertInfoDO = new ExpertInfoDO();
        BeanUtils.copyProperties(expertInfoDTO, expertInfoDO);
        if(expertInfoDTO.getSex()==1){
            userDO.setAvatar("https://nism.ytcata.com:3005/static/demand/man.svg");
            expertInfoDO.setAvatar("https://nism.ytcata.com:3005/static/demand/man.svg");
        }else {
            expertInfoDO.setAvatar("https://nism.ytcata.com:3005/static/demand/woman.svg");
            userDO.setAvatar("https://nism.ytcata.com:3005/static/demand/woman.svg");
        }
        expertInfoDO.setTaskId(taskList);
        expertInfoDAO.insert(expertInfoDO);
        userDO.setUsername(expertInfoDTO.getPhone());
        userDO.setNickname(expertInfoDTO.getName());
        String shaPassword = DigestUtil.sha256Hex("Aa123456");
        userDO.setPassword(shaPassword);
        userDO.setRole("normal");

        userDO.setBackground("https://img.zcool.cn/community/01d3275be6ab50a80121ab5deed64f.jpg@2o.jpg");
        userDO.setEmail(expertInfoDTO.getEmail());
        userDO.setIsExpert(1);
        userDO.setIndividual(expertInfoDTO.getName());
        userDO.setIsUserAuthentication(1);
        userDO.setIsAuthentication(1);
        userDO.setAuthenticationType("个人认证");
        userDAO.insert(userDO);
        return Result.success("增加专家成功");
    }

    @Override
    public Result updateExpert(ExpertInfoDTO expertInfoDTO) {
        ExpertInfoDO expertInfoDO = new ExpertInfoDO();
        BeanUtils.copyProperties(expertInfoDTO, expertInfoDO);
        expertInfoDAO.updateById(expertInfoDO);
        return Result.success("修改专家成功");
    }

    @Override
    public Result deleteExpert(Integer id) {
        ExpertInfoDO expertInfoDO = expertInfoDAO.selectById(id);
        userDAO.deleteByUsername(expertInfoDO.getPhone());
        expertInfoDAO.deleteById(id);
        return Result.success("删除专家成功");
    }

    @Override
    public Result getExpert(PageRequest pageRequest) {
        IPage<ExpertInfoDO> expertInfoDOIPage;
        Map<String, Object> params = pageRequest.getParams();
        Pagination pagination = pageRequest.getPagination();
        String name = MapUtils.getString(params, "name");
        if (name.equals("")) {
            expertInfoDOIPage = expertInfoDAO.selectByPage(pagination);
            return Result.success(expertInfoDOIPage);
        } else {
            expertInfoDOIPage = expertInfoDAO.selectByPageAndName(pagination, name);
            return Result.success(expertInfoDOIPage);
        }
    }


    @Override
    public Result getExpertType() {
        List<ExpertClassifyDO> expertClassifyDOS = expertClassifyDAO.selectAll();
        return Result.success(expertClassifyDOS);
    }

    @Override
    public Result productLists() {
        List<DemandDO> demandDOS = demandDAO.selectAll();
        List<DemandDO> collect = demandDOS.stream().filter(item -> item.getIsShow().equals(1)).collect(Collectors.toList());
        return Result.success(collect);
    }

    @Override
    public Result sendTask(ExpertTaskDTO expertTaskDTO) {
        int isFinish=0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String format = sdf.format(date);
            ExpertTaskDO expertTaskDO = new ExpertTaskDO();
            BeanUtils.copyProperties(expertTaskDTO, expertTaskDO);
            String startTime = expertTaskDTO.getStartTime();
            try {
                Date date_start = sdf.parse(startTime);
                Date today = sdf.parse(format);
                long startTimeMs = date_start.getTime();
                long time = today.getTime();

                if (time >= startTimeMs) {
                    expertTaskDO.setIsFinish(1);
                    isFinish=1;
                } else {
                    expertTaskDO.setIsFinish(0);
                }
                List<Integer> arrayList = new ArrayList<>();
                expertTaskDO.setOutcomeId(arrayList);
                expertTaskDAO.insert(expertTaskDO);

                for(int i=0;i<expertTaskDTO.getUsername().size();i++){
                    ExpertInfoDO expertInfoDO = expertInfoDAO.selectByUserName(expertTaskDTO.getUsername().get(i));
                    List<Integer> taskId = expertInfoDO.getTaskId();
                    taskId.add(expertTaskDO.getId());
                    expertInfoDO.setTaskId(taskId);
                    expertInfoDAO.updateById(expertInfoDO);
                    ExpertTaskStateDO expertTaskStateDO = new ExpertTaskStateDO();
                    expertTaskStateDO.setTaskId(expertTaskDO.getId());
                    expertTaskStateDO.setUsername(expertTaskDO.getUsername().get(i));
                    expertTaskStateDO.setIsFinish(isFinish);
                    expertTaskStateDO.setIsReceive(0);
                    expertTaskStateDAO.insert(expertTaskStateDO);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        return Result.success("发送任务成功");
    }

    @Override
    public Result listTask(HttpServletRequest request) {
        List<ExpertTaskVO> expertTaskVOS = new ArrayList<>();
        String username = JwtUtils.getUsername(request);
        ExpertInfoDO expertInfoDO = expertInfoDAO.selectByUserName(username);
        List<Integer> taskId = expertInfoDO.getTaskId();
         for(int i=0;i<taskId.size();i++){
             ExpertTaskDO expertTaskDO = expertTaskDAO.selectById(taskId.get(i));
             ExpertTaskStateDO expertTaskStateDO = expertTaskStateDAO.selectByTaskIdAndUserName(taskId.get(i), username);
             ExpertTaskVO expertTaskVO = new ExpertTaskVO();
              BeanUtils.copyProperties(expertTaskDO,expertTaskVO);
            expertTaskVO.setIsFinish(expertTaskStateDO.getIsFinish());
             expertTaskVO.setIsReceive(expertTaskStateDO.getIsReceive());
             expertTaskVOS.add(expertTaskVO);
         }
        return Result.success(expertTaskVOS);
    }

    @Override
    public Result expertScore(ExpertProductScoreDTO expertProductScoreDTO) {
        ExpertTaskDO expertTaskDO = expertTaskDAO.selectById(expertProductScoreDTO.getTaskId());
        ExpertOutcomeDO expertOutcomeDO = expertOutcomeDAO.selectById(expertProductScoreDTO.getOutcomeId());
        ExpertProductScoreDO expertProductScoreDO = new ExpertProductScoreDO();
        BeanUtils.copyProperties(expertProductScoreDTO, expertProductScoreDO);
        expertProductScoreDO.setTaskTitle(expertTaskDO.getTitle());
        expertProductScoreDO.setOutcomeTitle(expertOutcomeDO.getProductName());
        expertProductScoreDAO.insert(expertProductScoreDO);
        return Result.success("打分完成");
    }

    @Override
    public Result expertUpdateScore(ExpertProductScoreDTO expertProductScoreDTO) {
        ExpertProductScoreDO expertProductScoreDO = new ExpertProductScoreDO();
        BeanUtils.copyProperties(expertProductScoreDTO, expertProductScoreDO);
        expertProductScoreDAO.updateById(expertProductScoreDO);
        return Result.success("修改打分完成");
    }

    @Override
    public Result updateTask(ExpertTaskDTO expertTaskDTO) {
        int isFinish=-1;
        ExpertTaskDO expertTaskDO = new ExpertTaskDO();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String format = sdf.format(date);
        String startTime = expertTaskDTO.getStartTime();
        String endTime = expertTaskDTO.getEndTime();
        try {
            Date date_start = sdf.parse(startTime);
            Date endTimeMS = sdf.parse(endTime);
            Date today = sdf.parse(format);
            long endTimeMs = endTimeMS.getTime();
            long startTimeMs = date_start.getTime();
            long time = today.getTime();
           if(startTimeMs>time&&endTimeMs>time){
               isFinish=0;
           }else if(startTimeMs<time&&endTimeMs>time){
               isFinish=1;
           }else if(endTimeMs<time){
               isFinish=-1;
           }
        }catch (Exception e){
            e.printStackTrace();
        }

        for(int i=0;i<expertTaskDTO.getUsername().size();i++){
            ExpertTaskStateDO expertTaskStateDO = expertTaskStateDAO.selectByTaskIdAndUserName(expertTaskDTO.getId(), expertTaskDTO.getUsername().get(i));
            expertTaskStateDO.setIsFinish(isFinish);
            expertTaskStateDAO.updateById(expertTaskStateDO);
        }
        BeanUtils.copyProperties(expertTaskDTO, expertTaskDO);
        expertTaskDAO.updateById(expertTaskDO);
        return Result.success("修改任务成功");
    }

    @Override
    public Result deleteTask(Integer id) {
        ExpertTaskDO expertTaskDO = expertTaskDAO.selectById(id);
        expertTaskDAO.deleteById(id);
        List<ExpertInfoDO> expertInfoDOS = expertInfoDAO.selectAll();
        for(int i=0;i<expertInfoDOS.size();i++){
            List<Integer> taskId = expertInfoDOS.get(i).getTaskId();
            if(taskId.contains(id)){
                taskId.remove(id);
            }
            expertInfoDAO.updateById(expertInfoDOS.get(i));
        }
        List<String> username = expertTaskDO.getUsername();
        for(int i=0;i<username.size();i++){
            expertTaskStateDAO.deleteByTaskIdAndUserName(id,username.get(i));
            expertProductScoreDAO.deleteByTaskIdAndUserName(id,username.get(i));
        }
        return Result.success("删除任务成功");
    }

    @Override
    public Result listPageTask(PageRequest pageRequest) {
        IPage<ExpertTaskDO> expertTaskDOIPage;
        Map<String, Object> params = pageRequest.getParams();
        Pagination pagination = pageRequest.getPagination();
        String name = MapUtils.getString(params, "name");
        if (name.equals("")) {
            expertTaskDOIPage = expertTaskDAO.selectByPage(pagination);
            return Result.success(expertTaskDOIPage);
        } else {
            expertTaskDOIPage = expertTaskDAO.selectByPageAndName(pagination, name);
            return Result.success(expertTaskDOIPage);
        }
    }

    @Override
    public Result receiveTask(String op, Integer id, HttpServletRequest request) {
        String username = JwtUtils.getUsername(request);
        ExpertTaskStateDO expertTaskStateDO = expertTaskStateDAO.selectByTaskIdAndUserName(id, username);
        if (op.equals("1")) {
            expertTaskStateDO.setIsReceive(1);
            expertTaskStateDAO.updateById(expertTaskStateDO);
            return Result.success("接受任务");
        } else {
            expertTaskStateDO.setIsReceive(2);
            expertTaskStateDAO.updateById(expertTaskStateDO);
            return Result.success("拒绝任务");
        }
    }

    @Override
    public Result listExpertScore(PageRequest pageRequest, HttpServletRequest request) {
        IPage<ExpertProductScoreDO> expertProductScoreDOIPage;
        String username = JwtUtils.getUsername(request);
        Pagination pagination = pageRequest.getPagination();
        Map<String, Object> params = pageRequest.getParams();
        String name = MapUtils.getString(params, "name");
        if (name.equals("")) {
            expertProductScoreDOIPage = expertProductScoreDAO.selectByPageAndUserName(pagination, username);
            return Result.success(expertProductScoreDOIPage);
        } else {
            expertProductScoreDOIPage = expertProductScoreDAO.selectByPageLikeUserName(pagination, username, name);
        }

        return Result.success(expertProductScoreDOIPage);
    }

    @Override
    public Result listAllExpertScore(ExpertProductScoreDTO expertProductScoreDTO) {
        List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByTaskId(expertProductScoreDTO);
        return Result.success(expertProductScoreDOS);
    }

    @Override
    public Result listOutcome(PageRequest pageRequest, HttpServletRequest request) {
        List<TaskOutComeScoreVO> taskOutComeScoreVOS = new ArrayList<>();
        List<String> strings = new ArrayList<>();
        Pagination pagination = pageRequest.getPagination();
        String username = JwtUtils.getUsername(request);
        Map<String, Object> params = pageRequest.getParams();
        String id = MapUtils.getString(params, "id");
        String type = MapUtils.getString(params, "type");
        Integer taskId = Integer.valueOf(id);
        ExpertTaskDO expertTaskDO = expertTaskDAO.selectByPageAndTaskId(taskId);
        if (!CollectionUtils.isEmpty(expertTaskDO.getOutcomeId()) && expertTaskDO.getOutcomeId().size() >= 0) {
            List<ExpertOutcomeDO> expertOutcomeDOS = expertOutcomeDAO.selectByInOutcomeId(expertTaskDO.getOutcomeId());
            for (int j = 0; j < expertOutcomeDOS.size(); j++) {
                TaskOutComeScoreVO taskOutComeScoreVO = new TaskOutComeScoreVO();
                taskOutComeScoreVO.setProductName(expertOutcomeDOS.get(j).getProductName());
                taskOutComeScoreVO.setUsername(username);
                if(CollectionUtils.isEmpty(expertOutcomeDOS.get(j).getOutcomeFile())) {
                    taskOutComeScoreVO.setOutcomeUrl(null);
                    taskOutComeScoreVO.setFiletype(null);
                }else{
                    for(int i=0;i<expertOutcomeDOS.get(j).getOutcomeFile().size();i++){
                        String[] str = expertOutcomeDOS.get(j).getOutcomeFile().get(i).split("\\.");
                        if (str.length == 0) {
                            throw new RuntimeException("文件格式不正确");
                        }
                        String suffix = str[str.length - 1];
                        strings.add(suffix);
                    }
                    taskOutComeScoreVO.setOutcomeUrl(expertOutcomeDOS.get(j).getOutcomeFile());
                    taskOutComeScoreVO.setFiletype(strings);

                }
                TaskOutComeReviewDO taskOutComeReviewDO = taskOutComeReviewDAO.selectByTaskIdAndOutComeId(taskId, expertOutcomeDOS.get(j).getId());
                taskOutComeScoreVO.setOutcomeId(expertOutcomeDOS.get(j).getId());
                taskOutComeScoreVO.setEntName(expertOutcomeDOS.get(j).getEntName());
                taskOutComeScoreVO.setOnlineReview(taskOutComeReviewDO.getOnlineReview());
                taskOutComeScoreVO.setProductNumber(expertOutcomeDOS.get(j).getProductNumber());
                taskOutComeScoreVO.setProductImage(expertOutcomeDOS.get(j).getProductImage());
                taskOutComeScoreVO.setKeyword(expertOutcomeDOS.get(j).getKeyword());
                taskOutComeScoreVO.setTaskId(taskId);
                List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByTaskIdAndOutComeId(taskId, expertOutcomeDOS.get(j).getId(), username);
                if (!CollectionUtils.isEmpty(expertProductScoreDOS)) {
                    taskOutComeScoreVO.setOutcomeScore(expertProductScoreDOS.get(0).getScore());
                    taskOutComeScoreVO.setIsScore(1);
                } else {
                    taskOutComeScoreVO.setOutcomeScore(null);
                    taskOutComeScoreVO.setIsScore(0);
                }
                taskOutComeScoreVOS.add(taskOutComeScoreVO);
            }
        }
        if(type.equals("0")){
            return  Result.success(taskOutComeScoreVOS);
        }else if(type.equals("1")){
            List<TaskOutComeScoreVO> collect = taskOutComeScoreVOS.stream().filter(item -> item.getIsScore().equals(1)).collect(Collectors.toList());
            return  Result.success(collect);
        }else {
            List<TaskOutComeScoreVO> collect = taskOutComeScoreVOS.stream().filter(item -> item.getIsScore().equals(0)).collect(Collectors.toList());
            return  Result.success(collect);
        }
    }

    @Override
    public void onlinePreview(String url, HttpServletResponse response) {
        // 获取文件类型
        String[] str = url.split("\\.");
        if (str.length == 0) {
            throw new RuntimeException("文件格式不正确");
        }
        String suffix = str[str.length - 1];
        if (!"txt".equals(suffix) && !"doc".equals(suffix) && !"docx".equals(suffix) && !"xls".equals(suffix)
                && !"xlsx".equals(suffix) && !"ppt".equals(suffix) && !"pptx".equals(suffix)) {
            throw new RuntimeException("文件格式不支持预览");
        }
        try {
            InputStream in = FileConvertUtil.convertNetFile(url, suffix);
            OutputStream outputStream = response.getOutputStream();
            // 创建存放文件内容的数组
            byte[] buff = new byte[1024];
            // 所读取的内容使用n来接收
            int n;
            // 当没有读取完时,继续读取,循环
            while ((n = in.read(buff)) != -1) {
                // 将字节数组的数据全部写入到输出流中
                outputStream.write(buff, 0, n);
            }
            // 强制将缓存区的数据进行输出
            outputStream.flush();
            // 关闭流
            outputStream.close();
            in.close();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public Result showResults(PageRequest pageRequest) {
        IPage<ExpertOutcomeDO> outcomeDOIPage;
        Map<String, Object> params = pageRequest.getParams();
        String name = MapUtils.getString(params, "name");
        if (name.equals("")) {
            outcomeDOIPage = expertOutcomeDAO.selectByPage(pageRequest.getPagination());
            return Result.success(outcomeDOIPage);
        } else {
            outcomeDOIPage = expertOutcomeDAO.selectByPageLikeName(pageRequest.getPagination(), name);
            return Result.success(outcomeDOIPage);
        }
    }

    @Override
    public Result taskBindOutcome(ExpertTaskDTO expertTaskDTO){
        ExpertTaskDO expertTaskDO = new ExpertTaskDO();
        BeanUtils.copyProperties(expertTaskDTO, expertTaskDO);
        expertTaskDAO.updateById(expertTaskDO);
        return Result.success("绑定成功");
    }

    @Override
    public Result showOutcomeExpert(Integer taskId) {
        OutComeExpertVO outComeExpertVO = new OutComeExpertVO();
        List<OutComeVO> outComeVOS = new ArrayList<>();
        List<ExpertVO> expertVOList = new ArrayList<>();
        ExpertTaskDO expertTaskDO = expertTaskDAO.selectById(taskId);
        List<Integer> outcomeId = expertTaskDO.getOutcomeId();
        List<ExpertOutcomeDO> expertOutcomeDOS = expertOutcomeDAO.selectByInOutcomeId(outcomeId);

        for (ExpertOutcomeDO expertOutcomeDO : expertOutcomeDOS) {
            List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByTaskIdAdnOucComeId(taskId, expertOutcomeDO.getId());
            IntSummaryStatistics summaryStatistics = expertProductScoreDOS.stream().mapToInt(item->item.getScore()).summaryStatistics();
            OutComeVO outComeVO = new OutComeVO();
            outComeVO.setProductNumber(expertOutcomeDO.getProductNumber());
            double average = summaryStatistics.getAverage();
            BigDecimal bd = new BigDecimal(average);
            double v = bd.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            outComeVO.setAverageScore(v);
            outComeVO.setOutcomeId(expertOutcomeDO.getId());
            outComeVO.setOutcomeName(expertOutcomeDO.getProductName());
            outComeVOS.add(outComeVO);
        }
        List<ExpertInfoDO> expertInfoDOS = expertInfoDAO.selectAll();
        for (int i = 0; i < expertInfoDOS.size(); i++) {
            List<Integer> sourceTaskId = expertInfoDOS.get(i).getTaskId();
            if (!CollectionUtils.isEmpty(sourceTaskId) && sourceTaskId.contains(taskId)) {
                ExpertVO expertVO = new ExpertVO();
                expertVO.setName(expertInfoDOS.get(i).getName());
                expertVO.setUsername(expertInfoDOS.get(i).getPhone());
                expertVOList.add(expertVO);
            }
        }
        outComeExpertVO.setOutComeVOList(outComeVOS);
        outComeExpertVO.setExpertVOList(expertVOList);
        return Result.success(outComeExpertVO);
    }

    @Override
    public Result getScoreCondition(HttpServletRequest request, Integer taskId, Integer outcomeId) {
             Page<TaskOutComeScoreVO> page = new Page<>(1,5);
        List<TaskOutComeScoreVO> taskOutComeScoreVOS = expertOutcomeDAO.selectByCondition(page);
        return  Result.success(taskOutComeScoreVOS);
        }

    @Override
    public Result uploadFile(ExpertOutcomeDTO expertOutcomeDTO) {
        List<String> files = new ArrayList<>();
        if (expertOutcomeDTO.getOutcomeFile() != null) {
            for (int i = 0; i <expertOutcomeDTO.getOutcomeFile().size(); i++) {
                String image = ValidateCodeUtils.generateCode(4);
                if (!ObjectUtils.isEmpty(expertOutcomeDTO.getOutcomeFile())) {
                    String imagePath = FileUtils.saveMultipartFile2(expertOutcomeDTO.getOutcomeFile().get(i), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + image,
                            FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + image);
                    files.add(imagePath);
                }
                ExpertOutcomeDO expertOutcomeDO = expertOutcomeDAO.selectById(expertOutcomeDTO.getId());
                expertOutcomeDO.setOutcomeFile(files);
                expertOutcomeDAO.updateById(expertOutcomeDO);
            }
        }

        return Result.success("文件上传成功");
    }

    @Override
    public Result addOutCome(ExpertOutcomeDTO expertOutcomeDTO) {
        ExpertOutcomeDO expertOutcomeDO = new ExpertOutcomeDO();
        BeanUtils.copyProperties(expertOutcomeDTO,expertOutcomeDO);
        List<String> files = new ArrayList<>();
        if (expertOutcomeDTO.getOutcomeFile() != null) {
            for (int i = 0; i < expertOutcomeDTO.getOutcomeFile().size(); i++) {
                String image = ValidateCodeUtils.generateCode(4);
                if (!ObjectUtils.isEmpty(expertOutcomeDTO.getOutcomeFile())) {
                    String imagePath = FileUtils.saveMultipartFile2(expertOutcomeDTO.getOutcomeFile().get(i), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + image,
                            FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + image);
                    files.add(imagePath);
                }
                expertOutcomeDO.setOutcomeFile(files);
            }
        }
        expertOutcomeDAO.insert(expertOutcomeDO);
        return  Result.success("增加成果成功");
    }

    @Override
    public Result updateOutCome(ExpertOutcomeDTO expertOutcomeDTO) {
        ExpertOutcomeDO expertOutcomeDO = new ExpertOutcomeDO();
        BeanUtils.copyProperties(expertOutcomeDTO,expertOutcomeDO);
        List<String> files = new ArrayList<>();
        if (expertOutcomeDTO.getOutcomeFile() != null) {
            for (int i = 0; i < expertOutcomeDTO.getOutcomeFile().size(); i++) {
                String image = ValidateCodeUtils.generateCode(4);
                if (!ObjectUtils.isEmpty(expertOutcomeDTO.getOutcomeFile())) {
                    String imagePath = FileUtils.saveMultipartFile2(expertOutcomeDTO.getOutcomeFile().get(i), devHttpPrefix + DEMAND_PICTURE_PATH_PREFIX + image,
                            FileUtils.staticPath + DEMAND_PICTURE_PATH_PREFIX + image);
                    files.add(imagePath);
                }
                expertOutcomeDO.setOutcomeFile(files);
            }
        }
        expertOutcomeDAO.updateById(expertOutcomeDO);
        return  Result.success("修改成果成功");
    }

    @Override
    public Result deleteOutCome(Integer id) {
        expertOutcomeDAO.deleteById(id);
        return Result.success("删除成果成功");
    }

    @Override
    public Result addTaskExpert(ExpertTaskDTO expertTaskDTO) {
        ExpertTaskDO expertTaskDO = expertTaskDAO.selectById(expertTaskDTO.getId());

        for(int i=0;i<expertTaskDTO.getUsername().size();i++){
            List<String> username = expertTaskDO.getUsername();
            List<String> name = expertTaskDO.getName();
           name.add(expertTaskDTO.getName().get(i));
            username.add(expertTaskDTO.getUsername().get(i));
            expertTaskDO.setUsername(username);
            expertTaskDTO.setName(name);
            expertTaskDAO.updateById(expertTaskDO);
        }
        return Result.success("添加成功");
    }

    @Override
    public ExpertTaskSocreVO showTaskList() {
        ExpertTaskSocreVO expertTaskSocreVO = new ExpertTaskSocreVO();
        ArrayList<String> strings = new ArrayList<>();
        strings.add("product");
        strings.add("未打分成果");
        strings.add("已打分成果");
        expertTaskSocreVO.setDimensions(strings);
        List<Source4> sources=new ArrayList<Source4>();
        List<ExpertTaskDO> expertTaskDOS = expertTaskDAO.selectAll();
        for(int i=0;i<expertTaskDOS.size();i++){
            int haveScore=0;
            int total=expertTaskDOS.get(i).getUsername().size()*expertTaskDOS.get(i).getOutcomeId().size();
            String title = expertTaskDOS.get(i).getTitle();
            for(int j=0;j<expertTaskDOS.get(i).getOutcomeId().size();j++){

                List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByTaskIdAdnOucComeId(expertTaskDOS.get(i).getId(), expertTaskDOS.get(i).getOutcomeId().get(j));
                haveScore=haveScore+expertProductScoreDOS.size();
            }
            Source4 source4 = new Source4(title, total - haveScore,haveScore);
            sources.add(source4);
        }
        expertTaskSocreVO.setSource(sources);
        return expertTaskSocreVO;
    }

    @Override
    public  List<List<String>>  expertList() {
        List<List<String>> lists = new ArrayList<>();
        List<ExpertTaskDO> expertTaskDOS = expertTaskDAO.selectAll();
        List<ExpertTaskDO> collect = expertTaskDOS.stream().filter(item -> item.getId().equals(12)).collect(Collectors.toList());
        for(int i=0;i<collect.size();i++){
            List<String> username = collect.get(i).getUsername();
            for(int j=0;j<username.size();j++){
                if(username.get(j).equals("13897978821")){
                    continue;
                }
                ArrayList<String> arrayList = new ArrayList<>();
                ExpertInfoDO expertInfoDO = expertInfoDAO.selectByUserName(username.get(j));
                String a="<font color='#fff'  size='5'>" +expertInfoDO.getExpertNumber()+"</font>";
                arrayList.add(a);
                String haveOutCOme= String.valueOf(collect.get(i).getOutcomeId().size());
                List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByTaskAndUserName(collect.get(i).getId(), collect.get(i).getUsername().get(j));
                String finaOutCOme= String.valueOf(expertProductScoreDOS.size());
                String s="<font color='#00E5FF' size='5'>"+haveOutCOme+"</font>";
                String s1="<font color='#00E5FF' size='5'>"+finaOutCOme+"</font>";
                arrayList.add(s);
                arrayList.add(s1);
                lists.add(arrayList);
            }
        }
        return  lists;
    }

    @Override
    public List<List<String>> scoreList() {
        List<List<String>> lists = new ArrayList<>();
        List<ExpertTaskDO> expertTaskDOS = expertTaskDAO.selectAll();
        List<ExpertTaskDO> collect = expertTaskDOS.stream().filter(item -> item.getId().equals(12)).collect(Collectors.toList());
        for(int i=0;i<collect.size();i++){
                for(int a=0;a<collect.get(i).getOutcomeId().size();a++){
                    ArrayList<String> arrayList = new ArrayList<>();
                    Integer integer = collect.get(i).getOutcomeId().get(a);
                    ExpertOutcomeDO expertOutcomeDO = expertOutcomeDAO.selectById(integer);
                    String outcome="<font color='#00E5FF'  size='5'>"+expertOutcomeDO.getProductName()+"</font>";
                    arrayList.add(outcome);
                    for(int j=0;j<collect.get(i).getUsername().size();j++){
                        if(collect.get(i).getUsername().get(j).equals("13897978821")){
                            continue;
                        }
                        List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByTaskIdAndOutComeId(collect.get(i).getId(), collect.get(i).getOutcomeId().get(a), collect.get(i).getUsername().get(j));
                    if(!CollectionUtils.isEmpty(expertProductScoreDOS)){
                        Integer score = expertProductScoreDOS.get(0).getScore();
                       String score1= "<font color='#00E5FF'  size='5'>"+score+"</font>";
                        arrayList.add(score1);
                    }else {
                        String score="——";
                        arrayList.add(score);
                      }
                    }
                    List<ExpertProductScoreDO> expertProductScoreDOS1 = expertProductScoreDAO.selectByTaskIdAdnOucComeId(collect.get(i).getId(), collect.get(i).getOutcomeId().get(a));
                    if(CollectionUtils.isEmpty(expertProductScoreDOS1)){
                        arrayList.add("——");
                    }else {
                        IntSummaryStatistics summaryStatistics = expertProductScoreDOS1.stream().mapToInt(item->item.getScore()).summaryStatistics();
                        double average = summaryStatistics.getAverage();
                        BigDecimal bd = new BigDecimal(average);
                        double v = bd.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                        String score1= "<font color='#00E5FF'  size='5'>"+v+"</font>";
                        arrayList.add(score1);
                    }
                    lists.add(arrayList);

            }

        }
        return  lists;
    }
    public  String addString(String string){

          if(string.length()>=8){
              string = string.substring(0, 5) + "***" ;
              return  string;
          }else {
              return  string;
          }

    }
    @Override
    public List<List<String>> outcomeList() {
        List<List<String>> lists = new ArrayList<>();
        List<ExpertTaskDO> expertTaskDOS = expertTaskDAO.selectAll();
        List<ExpertTaskDO> collect = expertTaskDOS.stream().filter(item -> item.getId().equals(12)).collect(Collectors.toList());
              for(int i=0;i<collect.size();i++){
                for(int a=0;a<collect.get(i).getOutcomeId().size();a++){
                    ArrayList<String> arrayList = new ArrayList<>();
                    ExpertOutcomeDO expertOutcomeDO = expertOutcomeDAO.selectById(collect.get(i).getOutcomeId().get(a));
                    arrayList.add(expertOutcomeDO.getProductNumber());
                    arrayList.add(addString(collect.get(i).getTitle()));
                    String s = addString(expertOutcomeDO.getProductName());
                    String arr="<span color='#222222' style='margin-left:5px;'>"+s+"</span><br>";
                    arrayList.add((arr));
                    List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByTaskIdAdnOucComeId(collect.get(i).getId(),collect.get(i).getOutcomeId().get(a));
                    if(CollectionUtils.isEmpty(expertProductScoreDOS)){
                        String state="<font color='#FF554C'>成果状态：未打分</font>";
                        String state1="";
                        arrayList.add(state);
                        arrayList.add(state1);
                    }else {
                        IntSummaryStatistics summaryStatistics = expertProductScoreDOS.stream().mapToInt(item->item.getScore()).summaryStatistics();
                        String state="<font color='#FF554C'>成果状态：已打分</font>";
                        long sum = summaryStatistics.getSum();
                        arrayList.add(state);
                        String string="分值:"+sum;
                        arrayList.add(string);
                    }
                    lists.add(arrayList);
                }
            }
        return  lists;
    }

    @Override
    public List<Integer> OverviewDate() {
        List<ExpertTaskDO> expertTaskDOS = expertTaskDAO.selectAll();
        List<ExpertInfoDO> expertInfoDOS = expertInfoDAO.selectAll();
        List<ExpertOutcomeDO> expertOutcomeDOS = expertOutcomeDAO.selectAll();
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(expertTaskDOS.size());
        integers.add(expertOutcomeDOS.size());
        integers.add(expertInfoDOS.size());
        return integers;
    }

    @Override
    public Result reviewProgress() {
        double reviewProgress=1.0;
        return  Result.success(reviewProgress);
    }

    @Override
    public Result taskBindExpert(Integer id, String username, String name) {
        ExpertTaskDO expertTaskDO = expertTaskDAO.selectById(id);
        List<String> usernameList = expertTaskDO.getUsername();
        usernameList.add(username);
        expertTaskDO.setUsername(usernameList);
        List<String> nameList = expertTaskDO.getName();
        nameList.add(name);
        expertTaskDO.setName(nameList);
        expertTaskDAO.updateById(expertTaskDO);
        ExpertInfoDO expertInfoDO = expertInfoDAO.selectByUserName(username);
        List<Integer> taskId = expertInfoDO.getTaskId();
        taskId.add(id);
        expertInfoDAO.updateById(expertInfoDO);
        ExpertTaskStateDO expertTaskStateDO = new ExpertTaskStateDO();
        expertTaskStateDO.setUsername(username);
        expertTaskStateDO.setIsReceive(0);
        expertTaskStateDO.setIsFinish(1);
        expertTaskStateDO.setTaskId(id);
        expertTaskStateDAO.insert(expertTaskStateDO);
        return Result.success("绑定成功");
    }

    @Override
    public ExpertTaskSocreVO showTaskListv2() {
        ExpertTaskSocreVO expertTaskSocreVO = new ExpertTaskSocreVO();
        ArrayList<String> strings = new ArrayList<>();
        strings.add("product");
        strings.add("未打分成果");
        strings.add("已打分成果");
        expertTaskSocreVO.setDimensions(strings);
        List<Source4> sources=new ArrayList<Source4>();
        List<ExpertTaskDO> expertTaskDOS = expertTaskDAO.selectAll();
        for(int i=0;i<expertTaskDOS.size();i++){
            int haveScore=0;
            int total=expertTaskDOS.get(i).getUsername().size()*expertTaskDOS.get(i).getOutcomeId().size();
            String title = expertTaskDOS.get(i).getTitle();
            for(int j=0;j<expertTaskDOS.get(i).getOutcomeId().size();j++){

                List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByTaskIdAdnOucComeId(expertTaskDOS.get(i).getId(), expertTaskDOS.get(i).getOutcomeId().get(j));
                haveScore=haveScore+expertProductScoreDOS.size();
            }
            Source4 source4 = new Source4(title, total - haveScore,haveScore);
            sources.add(source4);
        }
        expertTaskSocreVO.setSource(sources);
        return expertTaskSocreVO;
    }

    @Override
    public List<List<String>> expertListv2() {
        List<List<String>> lists = new ArrayList<>();
        List<ExpertTaskDO> expertTaskDOS = expertTaskDAO.selectAll();
        List<ExpertTaskDO> collect = expertTaskDOS.stream().filter(item -> item.getId().equals(5)).collect(Collectors.toList());
        for(int i=0;i<collect.size();i++){
            List<String> username = collect.get(i).getUsername();
            for(int j=0;j<username.size();j++){
                ArrayList<String> arrayList = new ArrayList<>();
                ExpertInfoDO expertInfoDO = expertInfoDAO.selectByUserName(username.get(j));
                String a="<font color='#fff'  size='5'>" +expertInfoDO.getExpertNumber()+"</font>";
                arrayList.add(a);
                String haveOutCOme= String.valueOf(collect.get(i).getOutcomeId().size());
                List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByTaskAndUserName(collect.get(i).getId(), collect.get(i).getUsername().get(j));
                String finaOutCOme= String.valueOf(expertProductScoreDOS.size());
                String s="<font color='#00E5FF' size='5'>"+haveOutCOme+"</font>";
                String s1="<font color='#00E5FF' size='5'>"+finaOutCOme+"</font>";
                arrayList.add(s);
                arrayList.add(s1);
                lists.add(arrayList);
            }
        }
        return  lists;
    }

    @Override
    public List<List<String>> scoreListv2() {
        List<List<String>> lists = new ArrayList<>();
        List<ExpertTaskDO> expertTaskDOS = expertTaskDAO.selectAll();
        List<ExpertTaskDO> collect = expertTaskDOS.stream().filter(item -> item.getId().equals(5)).collect(Collectors.toList());
        for(int i=0;i<collect.size();i++){
            for(int a=0;a<collect.get(i).getOutcomeId().size();a++){
                ArrayList<String> arrayList = new ArrayList<>();
                Integer integer = collect.get(i).getOutcomeId().get(a);
                ExpertOutcomeDO expertOutcomeDO = expertOutcomeDAO.selectById(integer);
                String outcome="<font color='#00E5FF'  size='5'>"+expertOutcomeDO.getProductName()+"</font>";
                arrayList.add(outcome);
                for(int j=0;j<collect.get(i).getUsername().size();j++){
                    List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByTaskIdAndOutComeId(collect.get(i).getId(), collect.get(i).getOutcomeId().get(a), collect.get(i).getUsername().get(j));
                    if(!CollectionUtils.isEmpty(expertProductScoreDOS)){
                        Integer score = expertProductScoreDOS.get(0).getScore();
                        String score1= "<font color='#00E5FF'  size='5'>"+score+"</font>";
                        arrayList.add(score1);
                    }else {
                        String score="——";
                        arrayList.add(score);
                    }
                }
                List<ExpertProductScoreDO> expertProductScoreDOS1 = expertProductScoreDAO.selectByTaskIdAdnOucComeId(collect.get(i).getId(), collect.get(i).getOutcomeId().get(a));
                if(CollectionUtils.isEmpty(expertProductScoreDOS1)){
                    arrayList.add("——");
                }else {
                    IntSummaryStatistics summaryStatistics = expertProductScoreDOS1.stream().mapToInt(item->item.getScore()).summaryStatistics();
                    double average = summaryStatistics.getAverage();
                    BigDecimal bd = new BigDecimal(average);
                    double v = bd.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                    String score1= "<font color='#00E5FF'  size='5'>"+v+"</font>";
                    arrayList.add(score1);
                }
                lists.add(arrayList);

            }

        }
        return  lists;
    }

    @Override
    public List<List<String>> outcomeListv2() {
        List<List<String>> lists = new ArrayList<>();
        List<ExpertTaskDO> expertTaskDOS = expertTaskDAO.selectAll();
        List<ExpertTaskDO> collect = expertTaskDOS.stream().filter(item -> item.getId().equals(5)).collect(Collectors.toList());
        for(int i=0;i<collect.size();i++){
            for(int a=0;a<collect.get(i).getOutcomeId().size();a++){
                ArrayList<String> arrayList = new ArrayList<>();
                ExpertOutcomeDO expertOutcomeDO = expertOutcomeDAO.selectById(collect.get(i).getOutcomeId().get(a));
                arrayList.add(expertOutcomeDO.getProductNumber());
                arrayList.add(addString(collect.get(i).getTitle()));
                String s = addString(expertOutcomeDO.getProductName());
                String arr="<span color='#222222' style='margin-left:5px;'>"+s+"</span><br>";
                arrayList.add((arr));
                List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByTaskIdAdnOucComeId(collect.get(i).getId(),collect.get(i).getOutcomeId().get(a));
                if(CollectionUtils.isEmpty(expertProductScoreDOS)){
                    String state="<font color='#FF554C'>成果状态：未打分</font>";
                    String state1="";
                    arrayList.add(state);
                    arrayList.add(state1);
                }else {
                    IntSummaryStatistics summaryStatistics = expertProductScoreDOS.stream().mapToInt(item->item.getScore()).summaryStatistics();
                    String state="<font color='#FF554C'>成果状态：已打分</font>";
                    long sum = summaryStatistics.getSum();
                    arrayList.add(state);
                    String string="分值:"+sum;
                    arrayList.add(string);
                }
                lists.add(arrayList);
            }
        }
        return  lists;
    }

    @Override
    public List<Integer> OverviewDatev2() {
        List<ExpertTaskDO> expertTaskDOS = expertTaskDAO.selectAll();
        List<ExpertInfoDO> expertInfoDOS = expertInfoDAO.selectAll();
        List<ExpertOutcomeDO> expertOutcomeDOS = expertOutcomeDAO.selectAll();
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(expertTaskDOS.size());
        integers.add(expertOutcomeDOS.size());
        integers.add(expertInfoDOS.size());
        return integers;
    }

    @Override
    public Result reviewProgressv2() {
        double reviewProgress;
        Integer total = 0;
        List<ExpertTaskDO> expertTaskDOS = expertTaskDAO.selectAll();
        ExpertTaskDO expertTaskDO = expertTaskDOS.get(0);
        List<Integer> outcomeId = expertTaskDO.getOutcomeId();
        List<String> username = expertTaskDO.getUsername();
        total = outcomeId.size() * username.size();
        List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectById(expertTaskDO.getId());
        int size = expertProductScoreDOS.size();
        double duubleSize = size;
        double totalSize = total;
        reviewProgress = (duubleSize / totalSize);
        return  Result.success(reviewProgress);
    }

    @Override
    public Result showExpertScore(Integer id) {

        ExpertInfoDO expertInfoDO = expertInfoDAO.selectById(id);
        String name = expertInfoDO.getName();
        List<ExpertProductScoreDO> expertProductScoreDOS = expertProductScoreDAO.selectByUserName(name);
        return Result.success(expertProductScoreDOS);
    }


}
